package com.nbsaas.boot.queue.storage.impl;

import com.nbsaas.boot.queue.storage.TaskStorage;
import com.nbsaas.boot.queue.task.Task;
import com.nbsaas.boot.queue.task.TaskStatus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MemoryTaskStorage implements TaskStorage {
    private final Map<String, Task> taskMap;

    public MemoryTaskStorage() {
        this.taskMap = new ConcurrentHashMap<>();
    }

    @Override
    public void saveTask(Task task) {
        taskMap.put(task.getId(), task);
    }

    @Override
    public void updateTask(Task task) {
        taskMap.put(task.getId(), task);
    }

    @Override
    public Task getTask(String taskId) {
        return taskMap.get(taskId);
    }

    @Override
    public List<Task> getAllTasks() {
        return new ArrayList<>(taskMap.values());
    }

    @Override
    public List<Task> getPendingTasks() {
        return filterTasksByStatus(TaskStatus.PENDING);
    }

    @Override
    public List<Task> getRunningTasks() {
        return filterTasksByStatus(TaskStatus.RUNNING);
    }

    @Override
    public List<Task> getCompletedTasks() {
        return filterTasksByStatus(TaskStatus.COMPLETED);
    }

    @Override
    public List<Task> getFailedTasks() {
        return filterTasksByStatus(TaskStatus.FAILED);
    }

    @Override
    public void deleteTask(String taskId) {
        taskMap.remove(taskId);
    }

    private List<Task> filterTasksByStatus(TaskStatus status) {
        List<Task> result = new ArrayList<>();
        for (Task task : taskMap.values()) {
            if (task.getStatus() == status) {
                result.add(task);
            }
        }
        return result;
    }
} 